package com.le.tester.book.concurrentchallenge.atomicnoblocking15;

import java.util.concurrent.atomic.AtomicReference;

/**
 * createTime：2025-05-26 10:11
 * description：Michael-Scott非阻塞算法中的插入算法
 */
public class LinkedQueue<T> {
    private static class Node<T> {
        final T item;
        final AtomicReference<Node<T>> next;

        public Node(T item, AtomicReference<Node<T>> next) {
            this.item = item;
            this.next = new AtomicReference<>();
        }
    }

    private final Node<T> dummy = new Node<>(null, null);
    private final AtomicReference<Node<T>> head = new AtomicReference<>(dummy);
    private final AtomicReference<Node<T>> tail = new AtomicReference<>(dummy);

    public boolean put(T item) {
        Node<T> newNode = new Node<>(item, null);
        while (true) {
            Node<T> curTail = tail.get();
            Node<T> tailNext = curTail.next.get();
            if (curTail == tail.get()) {
                if (tailNext != null) {
                    tail.compareAndSet(curTail, tailNext);
                } else {
                    if (curTail.next.compareAndSet(null, newNode)) {
                        tail.compareAndSet(curTail, newNode);
                        return true;
                    }
                }
            }

        }
    }
}
